package thread;

import java.util.PriorityQueue;

//自己实现定时器
class MyTimerTask implements Comparable<MyTimerTask> {
    //要有一个执行的任务
    private Runnable runnable;
    //执行任务的时间
    private long time;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public long getTime() {
        return this.time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

class MyTimer {
    //使用一个数据结构来存储
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    public void schedule(Runnable runnable, long delay) {
        synchronized (this) {
            queue.offer(new MyTimerTask(runnable, delay));
            this.notify();
        }
    }

    public MyTimer() {
        //搞一个扫描线程
        Thread t = new Thread(() -> {
            //不断的扫描看最小时间是否到达运行时间
            while (true) {
                try {
                    synchronized (this) {
                        while (queue.isEmpty()) {
                            this.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            task.getRunnable().run();
                            queue.poll();
                        } else {
                            this.wait(task.getTime() - curTime);
                        }
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }


}

public class Demo14 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
        System.out.println("程序启动");
    }

}
